package com.vip.seata.at.business.util.rest;

import com.alibaba.fastjson.JSON;
import com.vip.seata.at.business.util.ApplicationHelper;
import com.vip.seata.at.business.util.SleuthHelper;
import com.vip.seata.at.business.util.StringPool;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author : evan.liu
 * @version V1.0
 * @Description: TODO RestTemplate 添加请求信息
 * @date Date : 2022年05月16日 12:00 上午
 */
@Slf4j
@Component
@ConditionalOnProperty(value = "feign.traceable.enabled",havingValue = "true",matchIfMissing = false)
public class RestTraceInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        log.info("Sleuth:{}",SleuthHelper.getSleuthTraceId());
        String application = ApplicationHelper.getApplicationName();
        String origin = SleuthHelper.getBaggageValue(StringPool.RPC_Origin_Application);
        if(StringUtils.isEmpty(origin)){
            SleuthHelper.addBaggage(StringPool.RPC_Origin_Application,application);
        }
        // FEIGN_Referer_Application 默认覆盖
        SleuthHelper.addBaggage(StringPool.RPC_Referer_Application,application);
        SleuthHelper.addBaggage(StringPool.RPC_Mode,StringPool.RPC_Mode_Http);

        HttpRequestWrapper requestWrapper = new HttpRequestWrapper(httpRequest);
        requestWrapper.getHeaders().add(SleuthHelper.SLEUTH_DEFAULT_BAGGAGE, JSON.toJSONString(SleuthHelper.getBaggage()));
        return clientHttpRequestExecution.execute(requestWrapper, bytes);
    }
}
